package com.jokey.vue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jokey.vue.mapper.MenuMapper;
import com.jokey.vue.model.Hr;
import com.jokey.vue.model.Menu;
import com.jokey.vue.model.MenuRole;
import com.jokey.vue.service.MenuRoleService;
import com.jokey.vue.service.MenuService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2021/11/26 15:36
 * @version: v1.0.0
 */
@Service
@CacheConfig(cacheNames = "menus_cache")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private MenuRoleService menuRoleService;

    @Override
    @Cacheable(key = "#root.methodName")
    public List<Menu> getAllMenus() {
        return baseMapper.getAllMenus();
    }

    @Override
    public List<Menu> getMenusByHrId() {
        return baseMapper.getMenusByHrId(((Hr) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
    }

    @Override
    @Cacheable
    public List<Menu> getAllMenusWithRole() {
        return baseMapper.getAllMenusWithRole();
    }

    @Override
    public List<Integer> getMidsByRid(Integer rid) {
        return baseMapper.getMidsByRid(rid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMenuRole(Integer rid, Integer[] mids) {
        menuRoleService.remove(new QueryWrapper<MenuRole>().eq("r_id", rid));
        if (mids == null || mids.length == 0) {
            return true;
        }
        List<MenuRole> menuRoleList = Arrays.stream(mids).map(mid -> new MenuRole(mid, rid)).collect(Collectors.toList());
        return menuRoleService.saveBatch(menuRoleList);
    }
}
